/*
 * @Description: 创建表弹窗
 * @Author: Rfan
 * @Date: 2022-05-27 15:09:30
 * @LastEditTime: 2022-06-11 16:54:16
 */

import { useEffect, useState } from 'react';
import { Button, Checkbox, Form, Modal, Typography } from 'antd';
import { addRepo, fetchRepoListByType } from '@/api/archivesType';
import { jsonClone } from '@/utils';
import { useArcTypeContext } from '../../contexts/ArcTypeContext';
import type { FC } from 'react';
import type { ICommonDialog } from '@/interfaces/global';
import type { IRepo } from '@/interfaces/archiveType';

interface RepoMgmtDialogProps extends ICommonDialog {
  data: any;
}

const RepoMgmtDialog: FC<RepoMgmtDialogProps> = (props) => {
  const { visible, data, onClose } = props;
  const { createAtRepoFunc } = useArcTypeContext();
  const [form] = Form.useForm();

  // 库列表
  const [repoList, setRepoList] = useState([]);
  // 保存按钮loading状态
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (visible) {
      fetchRepoListByType(data.atType, data.id).then((res) => {
        console.log('db list', res.data);
        const repoData = jsonClone(data);
        setRepoList(res.data);
        // 设置已选择的库
        repoData.archiveDbIdList = res.data
          .filter((item: IRepo) => item.createStatus)
          .map((item: IRepo) => item.id);

        // // 根据atType预制atLevel
        // if (!data.atLevel) {
        //   switch (data.atType) {
        //     case 0: {
        //       repoData.atLevel = 1;
        //       break;
        //     }
        //     case 1: {
        //       repoData.atLevel = 2;
        //       break;
        //     }

        //     default:
        //       break;
        //   }
        // }
        // if (data.containerUnit) {
        //   setBoxChecked(true);
        // } else {
        //   repoData.containerUnit = '盒';
        // }
        form.setFieldsValue(repoData);
      });
    }
  }, [visible]);

  /**
   * @description: 提交表单，触发onFinish方法，新增档案类型
   */
  const submitFunc = () => {
    form.submit();
  };
  const onFinish = (values: any) => {
    values.archiveTypeId = data.id;
    if (!values.archiveDbIdList) {
      values.archiveDbIdList = [];
    }
    // if (!boxChecked && values.containerUnit) {
    //   values.containerUnit = '';
    // }
    // console.log('submit repo', values);
    setLoading(true);
    createAtRepoFunc(values)
      .then(() => {
        onCancel();
      })
      .finally(() => {
        setLoading(false);
      });
  };

  /**
   * @description: 失败触发方法，如校验不通过
   * @param {any} errorInfo 错误信息
   */
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  /**
   * @description:  关闭弹窗触发
   */
  const onCancel = () => {
    onClose();
  };

  return (
    <Modal
      destroyOnClose
      title="库管理"
      visible={visible}
      width={550}
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" loading={loading} onClick={submitFunc}>
          保存
        </Button>
      ]}
    >
      <Form
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        preserve={false}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item>
          <Typography.Text type="secondary">库创建后将不能修改</Typography.Text>
        </Form.Item>
        <Form.Item name="archiveDbIdList">
          <Checkbox.Group>
            {repoList.map((repo) => (
              <Checkbox key={repo.id} value={repo.id} disabled={repo.createStatus}>
                {repo.description}
              </Checkbox>
            ))}
          </Checkbox.Group>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default RepoMgmtDialog;
